package com.example.order.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

/**
 * @description: TODO
 * @date 2021/2/11
 */
@Configuration
public class CustomerUserAuthenticationConverter extends DefaultAccessTokenConverter {

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 解决：oauth2通过SecurityContextHolder.getContext().getAuthentication().getPrincipal()获取到的是用户名？
     * @param userDetailsService
     */
    public CustomerUserAuthenticationConverter(UserDetailsService userDetailsService){
        DefaultUserAuthenticationConverter userAuthenticationConverter = new DefaultUserAuthenticationConverter();
        userAuthenticationConverter.setUserDetailsService(userDetailsService);
        super.setUserTokenConverter(userAuthenticationConverter);
    }

    @Bean
    public DefaultAccessTokenConverter defaultAccessTokenConverter() {
        DefaultAccessTokenConverter defaultAccessTokenConverter = new CustomerUserAuthenticationConverter(userDetailsService);
        return defaultAccessTokenConverter;
    }
}
